<template>
  <q-dialog
    v-model="chatDig"
    @show="() => {}"
    @hide="
      () => {
        pageParam.pageNum = 1
        rows = []
      }
    "
  >
    <q-card class="min-w-2xl" v-if="receiveUser">
      <div>
        <div class="text-h6 q-py-sm text-center">
          {{ receiveUser.username }}
        </div>
      </div>
      <q-scroll-area ref="scrollArea" style="width: 100%; height: 300px">
        <q-infinite-scroll ref="infiniteScroll" :offset="250" @load="onLoad" reverse>
          <template v-slot:loading>
            <div class="row justify-center q-my-md">
              <q-spinner color="primary" name="dots" size="40px" />
            </div>
          </template>
          <div class="q-px-md">
            <template v-for="(item, index) in rows" :key="index">
              <q-chat-message
                v-if="webStore.userInfo.id == item.sendUserId"
                :name="webStore.userInfo.username"
                :avatar="webStore.userInfo.avatar"
                text-html
                :text="[item.msg]"
                sent
                :stamp="item.createTime"
              />
              <q-chat-message
                v-else
                :name="item.sendUser.username"
                :avatar="item.sendUser.avatar"
                :text="[item.msg]"
                text-html
                :stamp="item.createTime"
              />
            </template>
          </div>
        </q-infinite-scroll>
      </q-scroll-area>

      <div class="q-pa-md row q-gutter-sm">
        <div class="col">
          <q-editor
            placeholder="文明交流，友好发言.."
            :toolbar="[]"
            @keyup.ctrl.enter.stop="
              () => {
                submit()
              }
            "
            v-model="editor"
            min-height="5rem"
          >
          </q-editor>
        </div>
        <div class="row items-center">
          <q-btn
            label="发送"
            @click="
              () => {
                submit()
              }
            "
          />
        </div>
      </div>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { inject, nextTick, onMounted, ref } from 'vue'
import { MsgType, useYuan } from 'src/use'
import type { EventBus } from 'quasar'
import { QInfiniteScroll, QScrollArea, useTimeout } from 'quasar'
import type { ApiType } from 'src/service/api'
import { chatInfo, chatSend } from 'src/service/api/chat'
import { useWebStore } from 'src/stores/webStore'
import { eventBusKey } from 'src/use'
import { storeToRefs } from 'pinia'

const bus = inject(eventBusKey) as EventBus<Api.EventBusType>
const { registerTimeout } = useTimeout()

const webStore = useWebStore()
const { chatDig, receiveUser } = storeToRefs(webStore)
const { Fail } = useYuan()
const scrollArea = ref<QScrollArea>()
const infiniteScroll = ref<QInfiniteScroll>()
const editor = ref('')

const pageParam = ref({
  receiveUserId: '',
  pageNum: 1,
  pageSize: 20,
  totalPage: 0,
  recordCount: 0,
})

type rowType = ApiType<typeof chatInfo>['Return']['rows'][0]
const rows = ref<Array<rowType>>([])

type loadType = Parameters<NonNullable<QInfiniteScroll['onLoad']>>

const onLoad = (index: loadType[0], done: loadType[1]) => {
  if (receiveUser.value) {
    pageParam.value.receiveUserId = receiveUser.value.id
    chatInfo(pageParam.value).then(({ data, error }) => {
      if (!error) {
        rows.value.splice(0, 0, ...data.rows)
        pageParam.value.pageNum = data.pageNum
        pageParam.value.pageSize = data.pageSize
        pageParam.value.totalPage = data.totalPage
        pageParam.value.recordCount = data.recordCount
        done()
        if (pageParam.value.pageNum == pageParam.value.totalPage || data.recordCount == 0) {
          infiniteScroll.value?.stop()
        } else {
          pageParam.value.pageNum++
        }
      }
    })
  }
}

const submit = () => {
  if (editor.value.trim().length == 0) {
    return Fail('内容不可为空')
  }
  if (receiveUser.value) {
    chatSend({
      receiveUserId: receiveUser.value.id,
      msg: editor.value,
    }).then(({ data, error }) => {
      if (!error) {
        rows.value.push(data)
        registerTimeout(() => {
          nextTick(() => {
            toEnd()
          })
        }, 200)
        editor.value = ''
      }
    })
  }
}

const toEnd = () => {
  scrollArea.value?.setScrollPercentage('vertical', 1, 200)
}

onMounted(() => {
  bus.on(MsgType.refreshChat, (msg) => {
    if (receiveUser.value) {
      if (msg.sendUserId == receiveUser.value.id) {
        rows.value.push(msg)
        registerTimeout(() => {
          nextTick(() => {
            toEnd()
          })
        }, 200)
      }
    }
  })
})
</script>

<style scoped></style>
